<template>
  <el-form inline @submit.native.prevent>
      <el-header style="display: flex; align-items: center; padding-left: 0;">
      <el-button
        class="back-btn"
        icon="el-icon-arrow-left"
        type="text"
        @click="goBack"
      >返回首页</el-button>
      <span class="header-title">用户后台管理</span>
      </el-header>
      <el-container>
      <el-main>
        <!-- 搜索与批量激活区域 -->
        <div style="margin-bottom: 18px; display: flex; align-items: center;">
          <el-input
            v-model="searchName"
            placeholder="搜索账号或昵称"
            style="width: 220px; margin-right: 12px;"
            clearable
            @keyup.enter.native="handleSearch"
          />
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
            style="margin-right: 16px;"
          >搜索</el-button>
          <el-button
            type="success"
            :disabled="selectedIds.length === 0"
            @click="handleBatchActivate"
          >批量激活</el-button>
        </div>

        <el-table :data="users" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="username" label="账号"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="role" label="角色">
            <template slot-scope="scope">
              <el-tag hit>
                <span v-if="scope.row.role === 'ADMIN'">管理员</span>
                <span v-else-if="scope.row.role === 'VIP'">会员用户</span>
                <span v-else>普通用户</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="nickname" label="昵称"></el-table-column>
          <el-table-column prop="avatar" label="头像">
            <template slot-scope="scope">
              <img :src="scope.row.avatar" alt="头像" style="width: 50px; height: 50px; border-radius: 50%;">
            </template>
          </el-table-column>
          <el-table-column prop="bio" label="个人简介"></el-table-column>
          <el-table-column prop="enabled" label="激活/停用">
            <template slot-scope="scope">
              <el-switch
                active-color="#13ce66"
                inactive-color="#ff4949"
                v-model="scope.row.enabled"
                :active-value="true"
                :inactive-value="false"
                :disabled="scope.row.role === 'ADMIN'"
                @change="scope.row.enabled ? activateUser(scope.row) : deactivateUser(scope.row)"
              ></el-switch>  
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="updatedAt" label="更新时间">
            <template slot-scope="scope">
              {{ formatDate(scope.row.updatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="toSky(scope.row)" type="primary" size="small">上天</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          @current-change="handlePageChange"
        ></el-pagination>
      </el-main>
      </el-container>
   </el-form>

</template>

<script>
import { getUserList,activateUser,deactivateUser,batchActivateUser } from '@/api/user'

export default {
  data() {
    return {
      users: [],
      total: 0,
      currentPage: 1,
      searchName: '',
      multipleSelection: [], // 用于存储多选框选中的用户
    };
  },
  created() {
    this.handelUserList(this.currentPage);
  },
  computed: {
    // 实时获取选中的用户ID数组
    selectedIds() {
      return this.multipleSelection.map(item => item.id);
    }
  },
  methods: {
    // 获取用户列表
    async handelUserList(page) {
      // 调用接口，支持分页和关键字
      const res = await getUserList({
        keyword: this.searchName,
        page: page - 1, // 后端一般从0开始
        size: 5
      });
      this.users = res.content || [];
      this.total = res.totalElements || 0;
    },
    // 处理分页变化
    async handlePageChange(page) {
      this.currentPage = page;
      this.handelUserList(page);
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.handelUserList(1);
    },
    // 格式化日期
    formatDate(date) {
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`;
    },
    //激活用户
    activateUser(user) {
      // 调用激活用户的API
      //console.log(`激活用户的id: ${user.id}`);
      activateUser(user.id)
        .then(() => {
          this.$message.success(`用户 ${user.username} 已激活`);
          this.handelUserList(this.currentPage); // 刷新用户列表
        })
        .catch(error => {
          this.$message.error(`激活用户失败: ${error.message}`);
        });
    },
    //停用用户
    deactivateUser(user) {
      // 调用停用用户的API
      //console.log(`停用用户的id: ${user.id}`);
      deactivateUser(user.id)
        .then(() => {
          this.$message.success(`用户 ${user.username} 已停用`);
          this.handelUserList(this.currentPage); // 刷新用户列表
        })
        .catch(error => {
          this.$message.error(`停用用户失败: ${error.message}`);
        });
    },
    // 处理多选框选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量激活
    async handleBatchActivate() {
      // 只取非管理员用户id
      const ids = this.multipleSelection.filter(u => u.role !== 'ADMIN').map(u => u.id);
      if (!ids.length) {
        this.$message.warning('请选择要激活的非管理员用户');
        return;
      }
      if (!this.selectedIds.length) {
        this.$message.warning('请选择要激活的用户');
        return;
      }
      try {
        await batchActivateUser(ids);
        this.$message.success('批量激活成功');
        this.handelUserList(this.currentPage);
      } catch (e) {
        this.$message.error('批量激活失败');
      }
    },
    // 返回首页
    goBack() {
      this.$router.push('/index');
    },
    // 上天按钮逻辑
    toSky(user) {
      // 这里可以添加上天的逻辑
      this.$message.success(`用户 ${user.username} 已上天!!你开心了吧哈哈哈哈哈`);
      // 例如，调用一个API或执行其他操作
      // this.skyApi(user.id).then(() => {
      //   this.$message.success(`用户 ${user.username} 已上天`);
      // });
    }
  },
};
</script>

<style scoped>
.back-btn {
  font-size: 16px;
  color: #409EFF;
  margin-right: 16px;
  padding-left: 8px;
  transition: color 0.2s;
}
.back-btn:hover {
  color: #66b1ff;
  background: #f4f8fb;
}
.header-title {
  font-size: 1.3rem;
  font-weight: bold;
  color: #222;
  letter-spacing: 2px;
}
</style>
